import {Howl, Howler} from 'howler';
import config from '@/config';

/**
 * 设置一些属性
 */
// 使用html5的audio播放(适应大型文件)
// Howler.html(true);

/**
 * 音效文件
 * @type {Howl}
 */
export const killBossSound = new Howl({src: require('@/assets/audio/killboss.mp3')});
export const captureSound = new Howl({src: require('@/assets/audio/capture.mp3')});
export const eatChessSound = new Howl({src: require('@/assets/audio/eatchess.mp3')});
export const moveSound = new Howl({src: require('@/assets/audio/move.mp3')});
export const gameWinSound = new Howl({src: require('@/assets/audio/win.mp3')});
export const peaceSound = new Howl({src: require('@/assets/audio/peace.mp3')});
export const gameFailSound = new Howl({src: require('@/assets/audio/fail.mp3')});
export const startSound = new Howl({src: require('@/assets/audio/start.mp3')});
export const timeoutSound = new Howl({src: require('@/assets/audio/timeout.mp3')});
export const btnSound = new Howl({src: require('@/assets/audio/btn.mp3')});
export const peopleEatSound = new Howl({src: require('@/assets/audio/peopleeat.mp3')});
export const messageSound = new Howl({src: require('@/assets/audio/message.mp3')});
// export const backgroundSound = new Howl({src: require('@/assets/audio/background.mp3')});


const soundList = [];

/**
 * 播放音效
 * @param sound
 */
export const playSound = (sound) => {
  if (config.music && sound) {
    sound.play();
    soundList.push(sound);
    sound.once('end', () => {
      removeSound(sound);
    })
  }
};

/**
 * 结束音乐
 * @param sound
 */
export const stopSound = (sound) => {
  if (sound) {
    sound.stop();
    removeSound(sound);
  }
}

/**
 * 暂停播放
 * @param sound
 */
export const pauseSound = (sound) => {
  if (sound) {
    sound.pause();
    removeSound(sound);
  }
}

/**
 * 暂停全部播放内容
 */
export const pauseAllSound = () => {
  soundList.forEach(sound => sound.pause());
}

/**
 * 启动全部播放内容
 */
export const startAllSound = () => {
  soundList.forEach(sound => {
    if (!sound.playing()) {
      sound.play();
    }
  });
}

/**
 * 移除音乐(内部方法)
 * @param sound
 */
const removeSound = sound => {
  const index = soundList.findIndex(item => item === sound);
  if (index !== -1) {
    soundList.splice(index, 1);
  }
}
